package cn.itcast.mytest;

import cn.itcast.n2.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

@Slf4j(topic = "c.test20")
public class Test01{
    public static void main(String[] args) {
        GuardObject guardObject = new GuardObject();

//        new Thread(() -> {
//            log.debug("等待结果");
//            List<String> list = (List<String>) guardObject.get(2000);
//            log.debug(""+list.size());
//        }, "t1").start();
//
//        new Thread(() -> {
//            log.debug("开始下载");
//            try {
//                List<String> download = Downloader.download();
//                guardObject.complete(download);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }, "t2").start();

        new Thread(() -> {
            log.debug("开始");
            Object o = guardObject.get(2000);
            log.debug("" + o);
        }, "t1").start();

        new Thread(() -> {
            log.debug("开始");
            Sleeper.sleep(1);
            guardObject.complete(null);
        }, "t2").start();
    }

}



class GuardObject {

    private Object response;

    //获取结果
    public Object get(long timeout){
        synchronized (this){
            long beginTime = System.currentTimeMillis();

            long passedTime = 0;

            while (response == null){
                long waittime = timeout - passedTime;

                if(waittime <= 0){
                    break;
                }

                try {
                    this.wait(waittime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                passedTime = System.currentTimeMillis() - beginTime;
            }

            return response;
        }
    }

    public void complete(Object response){
        synchronized (this){
            this.response = response;
            this.notifyAll();
        }
    }
}
